import axios from 'axios';
import { useRouter } from 'vue-router';
import { SignUtil } from '@/util/signin';
const router = useRouter();
const ServerCache = {};
const Client_ID="XcWebApp";
//与服务端协商好的客户端的目标地址,/login/oauth2/code/是固定值
const Redirect_URI='http://client.sso.com:3000/login/oauth2/code/user-server-client';
const Client_ID_PSWD_base64='Basic WGNXZWJBcHA6WGNXZWJBcHA=';
const BUSINESSFLAG="questionbank";
//加上业务系统标志
const addBusinessFlag=(value)=>{
	return BUSINESSFLAG+"_"+value;
}
const getAuServer = () => {
	const key = '/authServer';// 注意此处为了实现跨域，必须在vite.config.ts中配置跨域代理，用代理中的值代替模板服务器地址
	if (ServerCache[key]) {
		return ServerCache[key];
	} else {
		let server = axios.create({
			baseURL: key,
			timeout: 2000,
			withCredentials : true //该值表示携带cookie向服务端发送请求
		});
		ServerCache[key] = server;
		return server;
	}
};
const generateHeader=()=>{
	let _headers = {};
	_headers['Access-Control-Allow-Origin'] = '*';
	return _headers;
}
const appendFormSubmitHeader=(header)=>{
	if(header){
	header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
	}
}
const appendJsonSubmitHeader=(header)=>{
	if(header){
	header['Content-Type'] = 'application/json;charset=UTF-8';
	}
}
export const AuServerUtil = {
	fetch_csrf_token: async () => {
		let _server = getAuServer();
		let url = '/oauth2/csrf-token';
		let _headers = generateHeader();
		
		let _csrf = '';
		await _server
			.get(url,{},{
				headers: _headers
			})
			.then(response => {
				_csrf = response.data;
			})
			.catch(error => {
				console.log(error);
			});
		return _csrf;
	},
	toAuth: async(formData, authSuccess, authFailed) => {
		let _server = getAuServer();
		let _username=addBusinessFlag(formData.username);
		let _data = {
			username: _username,
			password: formData.password,
			checkCode:formData.checkCode
		};
		let _csrfobj=await AuServerUtil.fetch_csrf_token();
		let _headers = generateHeader();
		if (_csrfobj.parameterName) {
			_data[_csrfobj.parameterName] = _csrfobj.token;
			_headers[_csrfobj.headerName] = _csrfobj.token;
		}
		appendFormSubmitHeader(_headers);
		let url = '/login';
		await _server
			.post(url, _data, {
				headers: _headers
			})
			.then(res => {
				//console.log(res);
				let code=res.data['code']
				if (code==200) {
					authSuccess(_data["username"],res.data);
				} else {
					authFailed(res.data);
				}
			})
			.catch(error => {
				console.log(error);
				formData.message="用户名或密码错误！";
			});
	},
	toGetCode: async(formData, authSuccess, authFailed) => {
		let _server = getAuServer();
		let _data = {
			
				// response_type: 'code',
				// client_id: 'XcWebApp',
				// scope: 'all',
				// redirect_uri: Redirect_URI,
				// state:"348ise",
		}
		_data['params']={
			response_type: 'code',
			client_id: Client_ID,
			client_secret: Client_ID,
			scope: 'all',
			redirect_uri: Redirect_URI,
			//state:"348ise",
			//_csrf: formData.csrf
		};
		let _headers = generateHeader();
		if (formData.csrf.parameterName) {
			_data.params[formData.csrf.parameterName] = formData.csrf.token;
			_headers[formData.csrf.headerName] = formData.csrf.token;
		}
		appendFormSubmitHeader(_headers);
		_headers['Authorization'] = Client_ID_PSWD_base64;
		let url = '/oauth2/authorize';
		console.log(_data);
		await _server
			.get(url, _data, {
				headers: _headers
			})
			.then(res => {
				console.log(res);
				let _resData=res.data;
				let sourceUrl=res.config.url;
				let codeUrl=res.request.responseURL;
				console.log(sourceUrl)
				console.log(codeUrl)
				let parsedUrl =decodeURI(codeUrl);
				let _success=false;
				let _code="";
				if (parsedUrl.indexOf("?")!=-1){
					//说明有参数
					let paramStr=parsedUrl.substr(parsedUrl.indexOf("?")+1);//得到参数部分的字符串
					let allParams=paramStr.split("&");
					for( let _pair of allParams){
						let oneParam=_pair.split("=");
						if (oneParam[0]=='code'){
							_success=true;
							_code=oneParam[1];
							break;
						}
					}
				}
				if(_success){
					authSuccess(_code);
				}else{
					//if(_resData&&_resData.indexOf("<!DOCTYPE")>=0&&_resData.indexOf("state")>=0){
					//	let _restStr=_resData.substr(_resData.indexOf("state"));
					//	_restStr=_restStr.substr(_restStr.indexOf("value=")+7);
					//	let _end=_restStr.indexOf("\"");
					//	let _state=_restStr.slice(0,_end);
					//	_data.params['state'] =_state;
					//	AuServerUtil.toGetCode2(_data,authSuccess,authFailed);
					//}else{}
						authFailed(codeUrl);
				}
				console.log(parsedUrl)
				//window.location.href=codeUrl;  //vue3中这种方式重定位无效
			})
			.catch(error => {
				console.log(error);
			});
	},
	toGetCode2: async(_data, authSuccess, authFailed) => {
		let _server = getAuServer();
		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		//_headers['Content-Type'] = 'application/json;charset=UTF-8';
		//_headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
		
		let url = '/oauth2/authorize';
		console.log(_data);
		await _server
			.get(url, _data, {
				headers: _headers
			})
			.then(res => {
				console.log(res);
				let sourceUrl=res.config.url;
				let codeUrl=res.request.responseURL;
				console.log(sourceUrl)
				console.log(codeUrl)
				let parsedUrl =decodeURI(codeUrl);
				let _success=false;
				let _code="";
				if (parsedUrl.indexOf("?")!=-1){
					//说明有参数
					let paramStr=parsedUrl.substr(parsedUrl.indexOf("?")+1);//得到参数部分的字符串
					let allParams=paramStr.split("&");
					for( let _pair of allParams){
						let oneParam=_pair.split("=");
						if (oneParam[0]=='code'){
							_success=true;
							_code=oneParam[1];
							break;
						}
					}
				}
				if(_success){
					authSuccess(_code);
				}else{
					authFailed(codeUrl);
				}
				console.log(parsedUrl)
				//window.location.href=codeUrl;  //vue3中这种方式重定位无效
			})
			.catch(error => {
				console.log(error);
			});
	},
	toGetToken: async( formData, authSuccess, authFailed) => {
		let _server = getAuServer();
		let _data = {
			code: '',
			grant_type: 'authorization_code',
			redirect_uri: Redirect_URI,
			scope: 'all'
		};

		if (formData.code) {
			_data['code'] = formData.code;
		}
		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		//客户端id:密码的Base64编码
		_headers['Authorization'] = Client_ID_PSWD_base64;
		console.log(_data);
		let url = '/oauth2/token';
		await _server
			.post(url, _data, {
				headers: _headers
			})
			.then(res => {
				authSuccess(res.data);
			})
			.catch(error => {
				authFailed(error);
			});
	},
	toRefreshToken: async( refresh_token_str) => {
		if(!refresh_token_str){
			return;
		}
		let need2Refresh=SignUtil.needRefreshToken();
		if(true==need2Refresh){
			
		let _server = getAuServer();
		let _data = {
			client_id: Client_ID,
			grant_type: 'refresh_token',
			refresh_token:refresh_token_str,
			scope: 'all'
		};

		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		//客户端id:密码的Base64编码
		_headers['Authorization'] = Client_ID_PSWD_base64;
		console.log(_data);
		//刷新令牌也是相同的url，但参数不同
		let url = '/oauth2/token';
		await _server
			.post(url, _data, {
				headers: _headers
			})
			.then(res => {
				const _newToken=res.data;
				SignUtil.refreshToken(_newToken);
			})
			.catch(error => {
				console.log(error);
			});
	}
		}
};
